package com.hyts.serialize.execute;

import com.hyts.serialize.config.SerializeType;
import com.hyts.serialize.binary.BinarySerializeHandler;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.serialize.execute
 * author:Libo/Alex
 * create-date:2019-06-21 22:45
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: 序列化执行器
 */
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SerializeExecutor {


    /**
     * 序列化服务
     */
    SerializeType serializeType;

    /**
     * 序列化
     * @param value
     * @return
     */
    public  byte[] serialize(Object value){
        return (byte[]) switchHandler(serializeType).serialize(value);
    }

    /**
     * 反序列化
     * @param value
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T deserialize(byte[] value,Class<T> clazz){
        return (T) switchHandler(serializeType).deserialize(value,clazz);
    }

    /**
     * 切换序列化类型服务
     * @param serializeType
     * @return
     */
    private BinarySerializeHandler switchHandler(SerializeType serializeType){
        //序列化类型
        if(serializeType == null)
            serializeType = SerializeType.PROTOSTUFF;
        try {
            BinarySerializeHandler handler = (BinarySerializeHandler) serializeType.getClazz().newInstance();
            handler.build();
            return handler;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
